# 1.导包
from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

# 2.继承 类
from rest_framework_jwt.utils import jwt_payload_handler

from apps.users.models import User
import re

from meiduo_mall.settings.dev import logger

# 封装 生成  激活链接 的 函数
def generate_verify_email_url(user):
    # http://www.meiduo.site:8000/emails/verification/?token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2NjE5ODk4MywiZXhwIjoxNTY2MjAyNTgzfQ.eyJ1c2VyX2lkIjo2LCJlbWFpbCI6ImxpdWNoZW5nZmVuZzY2NjZAMTYzLmNvbSJ9.okIKKAHjeskFild3EZeK3034N2r0vMb_tvUaVA7h4qPdfxmsDG4JvzXsTLl2_98Ln6rpWN4EmAdrdthZeG2DdQ
    host_url = settings.EMAIL_ACTIVE_URL
    data_dict = {
        'user_id':user.id,
        'email':user.email
    }
    from utils.secret import SecretOauth
    dumps_params = SecretOauth().dumps(data_dict)
    verify_url = host_url + "?token=" + dumps_params

    return verify_url

# 封装校验用户名的函数
def get_user_by_account(account):
    try:
        if re.match('^1[345789]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        logger.error('用户对象不存在')
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 后台登陆无request
        if request is None:
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            if user.check_password(password):
                return user

        # 前台登陆有request
        else:
            # 实现多账号 校验用户名和 手机号
            user = get_user_by_account(username)

            # 校验密码是否正确
            if user and user.check_password(password):
                return user


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }


def meiduo_payload_handler(user):
    # 重复某个方法中的代码，直接调用执行
    payload = jwt_payload_handler(user)

    # 删除邮箱
    del payload['email']

    # 添加手机号
    payload['mobile'] = user.mobile

    return payload
